<template>
  <div>
    <div class="tab-wrap flex-row">
      <ul class="flex-row item">
        <li :class="{'cur1':indexPage=='1'}" @click="indexPage ='1'">待指派{{orders.list1?orders.list1.length:'0'}}</li>
        <li :class="{'cur1':indexPage=='2'}" @click="indexPage ='2'">配送中{{orders.list2?orders.list2.length:'0'}}</li>
        <li :class="{'cur1':indexPage=='3'}" @click="indexPage ='3'" >
          <el-badge style='font-size: 15px' :value="orders.list3.length?orders.list3.length:''"
            :max="99" class="num-int" >异常{{orders.list3.length==0?0:''}}
          </el-badge>
        </li>
        <li :class="{'cur1':indexPage=='4'}" @click="indexPage ='4'">超时完成{{orders.list4?orders.list4.length:'0'}}</li>
      </ul>
      <div class="shop-state fle-ver">
        <div class="state flex-row">营业时间 <span>运营中</span></div>
        <div class="time">00:00 --23:59</div>
      </div>
    </div>
    <div class="bg-empty"></div>
    <div class="tab1 padding-top" v-show="indexPage == '1'">
      <div class="p-left">
        <div class="flex head">
          <div class="shopers">当前骑手：
            <span class="shop" v-if="Object.keys(curShoperMsg).length > 0">
              <span class="name">{{curShoperMsg.name}}</span>
              <span class="data">(<em>{{curShoperMsg.jieDanNum}}/</em><em>{{curShoperMsg.peiSongNum}}/</em>{{curShoperMsg.totalNum}})</span>
            </span>
            <span v-else>暂未选择骑手</span>
          </div>
          <el-button type="primary" plain icon="el-icon-refresh" @click="resall()"></el-button>
        </div>
        <div class="order">
          <!-- <div class="o-btns flex-row-ver">
               <span :class="{'cur':assignType==1}">正在指派</span>
               <span :class="{'cur':assignType==2}">预指派</span>
           </div>-->
          <ul class="o-list" id="order-list">
            <li v-for="item in orders.list1" :key="item.id"
                draggable="true"
                @dragstart="dragOrders($event,item)"
                :class="{'cur':curlistOrder.ids.indexOf(item.id)>=0 }" @click="orderLine(item)">
              <div class="flex c-dui row">
                <div class="flex">
                  <span class="get flex-row-ver">取</span>
                  <span class="mat shop pt"><em style='color:#e65151'>【{{item.type|capitalType}}】</em>{{item.fromType =='NEARBY'?'【骑手就近购买】':item.diaoDuFromAddress}}</span>
                </div>
                <span class="dui el-icon-circle-check"></span>
              </div>
              <div class="flex row" >
                <span class="shou flex-row-ver">送</span>
                  <span class="mat">{{item.diaoDuToAddress}}</span>
              </div>

              <div class="flex row" style="margin-left:30px;">
                <span><time-out-pt :endTime='item.deliveryDuration' :createTime='item.timePaid'></time-out-pt>/</span>
                <span class="adjust-t"><adjust-out-pt :createTime='item.timePaid'></adjust-out-pt></span>
              </div>

              <div class="flex row" style="margin-left:30px;">
                <span v-if="capStatus(item.status) =='2' " class="tip">骑手未接单,请及时处理</span>
                <span class="tip2" v-else>骑手已接单,请刷新重试</span>
                <span class="tip"></span>
              </div>
            </li>
          </ul>
          <div class="butns">
            <el-button style="margin: 0" type="success" plain size="mini" @click="confirmToSendASingle()">派单</el-button>
          </div>
        </div>
      </div>
      <div class="p-right">
        <div class="flex head">
          <!--<el-input placeholder="搜骑手,为空查询全部" v-model="name" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" ></el-button>
          </el-input>-->
        </div>
        <div class="o-btns flex-row-ver">
          <span :class="{'cur2':type==1}" @click="switchTheRider(1)">开工<br/>{{shopworkList.workingNum}}</span>
          <span :class="{'cur2':type==2}" @click="switchTheRider(2)">下班<br/>{{shopworkList.noWorkingNum}}</span>
        </div>
        <ul class="ul-s" v-if="type ==1" id="shopper-list" style="position: relative">
          <li class="flex-ver" v-for="item in shopworkList.workingList"
              :key="item.id" :class="{'cur':curlistShoper==item.id}"
              @drop="orderDrop($event,item)"
              @dragover="allowDrop($event)"
              @click="curhandShoper(item)"
              @contextmenu.prevent="sendOrders(item.id)"
              style="cursor: pointer">
            <div class="flex-row row">
              <span class="name">{{item.name}}</span>
              <span class="data"><em>{{item.jieDanNum}}/</em><em>{{item.peiSongNum}}/</em>{{item.totalNum}}</span>
            </div>
            <div class="tel">{{item.munber}}</div>
          </li>
        </ul>
        <ul class="ul-s" v-if="type ==2" style="background: #f1f1f1">
          <li class="flex-ver" v-for="item in shopworkList.noWorkingList" :key="item.id">
            <div class="flex-row row">
              <span class="name">{{item.name}}</span>
              <span class="data"><em>{{item.jieDanNum}}/</em><em>{{item.peiSongNum}}/</em>{{item.totalNum}}</span>
            </div>
            <div class="tel">{{item.munber}}</div>
          </li>
        </ul>
      </div>
      <div id="container-dd" class="adjust-location base-diy-map"></div>
    </div>
    <div class="tab2 padding-top" v-show="indexPage == '2'">
      <div class='base-table-wrap'>
        <el-row class="item-sub" type="flex">
          <span :class="{'cur1':statu =='1'}"
                @click="statu ='1'">全部{{orders.list2?orders.list2.length:'0'}}</span>
          <span :class="{'cur1':statu =='2'}"
                @click="statu ='2'">待取货{{orders.list5?orders.list5.length:'0'}}</span>
          <span :class="{'cur1':statu =='3'}"
                @click="statu ='3'">待送达{{orders.list6?orders.list6.length:'0'}}</span>
        </el-row>
        <el-table v-show="statu =='1'" :data="orders.list2" style="width: 100%"
                  :default-sort="{prop: 'date', order: 'descending'}" >
          <el-table-column label="收货人" min-width="180px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.diaoDuToUserName}}|{{scope.row.diaoDuToMobile}}</div>
              <div>{{scope.row.diaoDuToAddress}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="订单号" min-width="120" align="center" />
          <el-table-column label="配送费用" min-width="100px" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.amountPaid/100||0}}{{comConfig.unit}}</div>
              <div>{{scope.row.paid?paySatus(scope.row.channel): '未支付'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="120px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopperName }}</div>
              <div>{{scope.row.shopperMobile}}</div>
            </template>
          </el-table-column>
          <el-table-column prop='distance' :label="`距离(${comConfig.mLengthUnit})`" min-width="80px" align="center">
            <template slot-scope="scope">
              {{comConfig.mLengthUnit(scope.row.distance)}}
            </template>
          </el-table-column>
          <el-table-column label="距超时" min-width="120px" align="center">
            <template slot-scope="scope">
              <yue-time-out-pt :endTime='scope.row.deliveryDuration' :createTime='scope.row.timePaid' />
            </template>
          </el-table-column>
          <el-table-column prop="timeTaken" label="接单时间" min-width="120px" sortable align="left" />
          <el-table-column prop="statstr" label="状态" min-width="80px" align="center">
            <template slot-scope="scope">
             {{scope.row.status|capitalStatus}}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button style="margin: 0 0 5px 0" type="warnning" size="mini"
                @click="reassigningTheRider(scope.row.id,scope.row.driverId)" round plain>订单改派
              </el-button>
              <el-dropdown>
                <el-button  type="danger" size="mini" round plain >更改状态</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="capStatus(scope.row.status)<=3 ">
                    <el-button type='text' @click="alterTheState(scope.row.id,'PICKED')">已取货</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="capStatus(scope.row.status)<=4 ">
                    <el-button type='text' @click="alterTheState(scope.row.id,'COMPLETED')">订单完成</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-table v-show="statu =='2'" :data="orders.list5" style="width: 100%"
                  :default-sort="{prop: 'date', order: 'descending'}" >
          <el-table-column label="收货人" min-width="180px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.diaoDuToUserName}}|{{scope.row.diaoDuToMobile}}</div>
              <div>{{scope.row.diaoDuToAddress}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="订单号" min-width="120" align="center"></el-table-column>
          <el-table-column label="配送费用" min-width="100px" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.amountPaid/100||0}}{{comConfig.unit}}</div>
              <div>{{scope.row.paid?paySatus(scope.row.channel): '未支付'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="120px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopperName}}</div>
              <div>{{scope.row.shopperMobile}}</div>
            </template>
          </el-table-column>
          <el-table-column prop='distance' label="距离(米)" min-width="80px" align="center" />
          <el-table-column label="距超时" min-width="120px" align="center">
            <template slot-scope="scope">
              <yue-time-out-pt :endTime='scope.row.deliveryDuration' :createTime='scope.row.timePaid'/>
            </template>
          </el-table-column>
          <el-table-column prop="timeTaken" label="接单时间" min-width="120px" sortable align="left" />
          <el-table-column prop="statstr" label="状态" min-width="80px" align="center">
            <template slot-scope="scope">
              {{scope.row.status|capitalStatus}}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button style="margin: 0 0 5px 0" type="warnning" size="mini"
                @click="reassigningTheRider(scope.row.id,scope.row.driverId)" round plain>订单改派
              </el-button>
              <el-dropdown>
                <el-button  type="danger" size="mini" round plain >更改状态</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button type='text' @click="alterTheState(scope.row.id,'PICKED')">已取货</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type='text' @click="alterTheState(scope.row.id,'COMPLETED')">订单完成</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-table v-show="statu =='3'" :data="orders.list6" style="width: 100%"
          :default-sort="{prop: 'date', order: 'descending'}" >
          <el-table-column label="收货人" min-width="180px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.diaoDuToUserName}}|{{scope.row.diaoDuToMobile}}</div>
              <div>{{scope.row.diaoDuToAddress}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="订单号" min-width="120" align="center" />
          <el-table-column label="配送费用" min-width="100px" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.amountPaid/100||0}}{{comConfig.unit}}</div>
              <div>{{scope.row.paid?paySatus(scope.row.channel): '未支付'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="120px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopperName}}</div>
              <div>{{scope.row.shopperMobile}}</div>
            </template>
          </el-table-column>
          <el-table-column prop='distance' label="距离(米)" min-width="80px" align="center" />
          <el-table-column label="距超时" min-width="120px" align="center">
            <template slot-scope="scope">
              <yue-time-out-pt :endTime='scope.row.deliveryDuration' :createTime='scope.row.updateTime' />
            </template>
          </el-table-column>
          <el-table-column prop="timeTaken" label="接单时间" min-width="120px" sortable align="left" />
          <el-table-column prop="statstr" label="状态" min-width="80px" align="center">
            <template slot-scope="scope">
              {{scope.row.status|capitalStatus}}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button style="margin: 0 0 5px 0" type="warnning" size="mini"
                @click="reassigningTheRider(scope.row.id,scope.row.driverId)" round plain>订单改派
              </el-button>
              <el-dropdown>
                <el-button  type="danger" size="mini" round plain >更改状态</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button type='text' @click="alterTheState(scope.row.id,'COMPLETED')">订单完成</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="选中骑手" v-dialogDrag :visible.sync="dialogTableVisible" width="600px" :close-on-press-escap="true">
        <div class="big-class">
          <el-radio-group v-model="radioShopper">
            <el-radio v-for="item in shopworkList.workingList" :key="item.id" :label="item.id">{{item.name}}</el-radio>
          </el-radio-group>
        </div>
        <el-button class="save" @click="saveChangeShopper()" type="primary">保存</el-button>
      </el-dialog>
    </div>
    <div class="tab3 padding-top" v-show="indexPage == '3'">
      <div class="base-table-wrap" >
        <el-table :data="orders.list3" style="width: 100%" :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="收货人" min-width="180px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.diaoDuToUserName}}|{{scope.row.diaoDuToMobile}}</div>
              <div>{{scope.row.diaoDuToAddress}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="订单号" min-width="120" align="center" />
          <el-table-column label="配送费用" min-width="100px" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.amountPaid/100||0}}{{comConfig.unit}}</div>
              <div>{{scope.row.paid?paySatus(scope.row.channel): '未支付'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="120px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopperName}}</div>
              <div>{{scope.row.shopperMobile}}</div>
            </template>
          </el-table-column>
          <el-table-column prop='distance' label="距离(米)" min-width="80px" align="center" />
          <el-table-column label="异常原因" min-width="120px" align="center">
            <template slot-scope="scope">
              用户申请取消
            </template>
          </el-table-column>
          <el-table-column prop="timeTaken" label="接单时间" min-width="120px" sortable align="left" />
          <el-table-column prop="statstr" label="状态" min-width="80px" align="center">
            <template slot-scope="scope">
              {{scope.row.status|capitalStatus}}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="tab4 padding-top" v-show="indexPage == '4'">
      <div class="base-table-wrap">
        <el-table :data="orders.list4" style="width: 100%" :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="收货人" min-width="180px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.diaoDuToUserName}}|{{scope.row.diaoDuToMobile}}</div>
              <div>{{scope.row.diaoDuToAddress}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="订单号" min-width="120" align="center" />
          <el-table-column label="配送费用" min-width="100px" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.amountPaid/100||0}}{{comConfig.unit}}</div>
              <div>{{scope.row.paid?paySatus(scope.row.channel): '未支付'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="120px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopperName}}</div>
              <div>{{scope.row.shopperMobile}}</div>
            </template>
          </el-table-column>
          <el-table-column prop='distance' label="距离(米)" min-width="80px" align="center" />
          <el-table-column  label="超时时长"  min-width="120px" align="left">
            <template slot-scope="scope">
              <span v-html='$options.filters.capitalize(scope.row.timePaid,scope.row.timeTaken,scope.row.deliveryDuration)'></span>
            </template>
          </el-table-column>
          <el-table-column prop="timeTaken" label="接单时间" min-width="120px" sortable align="left" />
          <el-table-column prop="statstr" label="状态" min-width="80px" align="center">
            <template slot-scope="scope">
              {{scope.row.status |capitalStatus}}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--订单提示音  controls="controls"-->
      <div class="listen" >
        <audio id="appleline"><source :src="appleline"/> </audio>
      </div>
    </div>
  </div>
</template>

<script>
  import yueTimeOutPt from './yueTimeOutPt'
  import timeOutPt from './timeOutPt'
  import adjustOutPt from './adjustOutPt'
  import { paySatus } from '@/utils/ptkc'
  import adjust2 from '../mixins/adjust2'
  import applelines from '@/assets/video/appleline.mp3'
  import { paotuiOrderSchedulingList, paotuiFindShopper } from '@/api/adjust'
  export default {
    mixins: [adjust2],
    components: { timeOutPt, adjustOutPt, yueTimeOutPt },
    props: {
      videoSet: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        paySatus: paySatus,
        curlistOrder: {ids: [], markers: [], order: []}, //当前选择的正在指派订单id 和地图标记
        shopName: '', //搜索骑手名称关键子
        type: 1, //骑手上班或下班切换
        shopworkList: {}, //骑手
        curlistShoper: '', //当前被点击的起手
        openShopOrder: null,//当前仅仅显示这个起手的信息和收取
        openShopOrderList: [], //当前仅仅显示这个起手下的所有订单
        shoperMarkers: {ids: [], markers: []}, //骑手标记
        curShoperMsg: {},  // 当前选中的骑手
        dialogTableVisible: false, //弹出层
        radioShopper: '', //选中的骑手
        curShopper: '', //当前骑手
        radioOrderId: '', //选中的订单
        statu: '1', //订单状态
        newPage: 1, //默认
        orders: { //订单所有数据
          agentbusiness: {},
          list1: [],
          list2: [],
          list3: [],
          list4: [],
          list5: [],
          list6: [],
        },
        indexPage: '1', //indexPage
        lockReconnect: false, // websocke 防重复
        stopWebSocket: false, // 页面关闭
        timeoutObj: null, // 服务器未相应倒计时
        reastWebsocket: null, // 重启websocket倒计时
        restOrderTime: null, // 重启接口倒计时
        ws: null, // websocket 对象
        neworder: null, // 订单语言
        appleline: applelines // 语音文件
      }
    },
    filters: {
      capitalStatus(status) {
        const a = ['CANCELED','CREATED',  'PAID', 'TAKEN', 'PICKED', 'COMPLETED']
        const b = ['取消', '下单', '付款', '骑手接单', '已取货','完成']
        return a.indexOf(status) > -1 ? b[a.indexOf(status)] : '未知'
      },
      capitalType(type) {
        const a = ['DAIGOU', 'QUSONGJIAN']
        const b = ['代购', '取件']
        return a.indexOf(type) > -1 ? b[a.indexOf(type)] : '未知'
      },
      capitalize(time, readytime,last) {
        let times = time
        let readytimes = readytime
        if (times && readytimes && last) {
          let endTime = new Date(times.replace(/-/g, "/")).getTime() + last*60000
          let nowTime = new Date(readytimes.replace(/-/g, "/")).getTime()
          let time = Math.ceil((nowTime - endTime) / 1000 / 60)
          if (time >= '60') {
            let h = Math.floor(time / 60)
            let m = time % 60 == 0 ? '' : `${time % 60}分`
            return `<span style='color:red;'>超时${h}小时${m}</span>`
          } else {
            if(time<10) return `超时${time}分`
            else return `<span style='color:red;'>超时${time}分</span>`
          }
        } else {
          return `未知`
        }
      },
    },
    watch:{
      'orders.list1':{
        handler(val,oldval){
          this.$emit('ptWebsockerNum',this.orders.list1.length)
        },
        deep:true
      }
    },
    methods: {
      capStatus(status) {
        const a = ['CANCELED', 'CREATED', 'PAID', 'TAKEN', 'PICKED', 'COMPLETED']
        return a.indexOf(status)
      },
      capType(type) {
        const a = ['DAIGOU', 'QUSONGJIAN']
        return a.indexOf(type)
      },
      switchTheRider(int) { //本地切换上下班骑手
        this.type = int
      },
      dragOrders(ev,item) { // 拖拽开始
        ev.dataTransfer.setData("Te",JSON.stringify(item));
      },
      orderDrop(ev,item) { // 拖拽释放
        ev.preventDefault();
        var data=ev.dataTransfer.getData("Te");
        this.$confirm(`是否指派给${item.name}？`, '拖动派单提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'success',
          center: true
        }).then(() => {
          this.confirmToSendASingle(JSON.parse(data).id,item.id)
        }).catch(() => {
          this.$message.info('已取消派单操作')
        })
      },
      allowDrop(ev) { // 拖拽
        ev.preventDefault()
      },
      confirmToSendASingle(orderId,shoperId)  { //指派订单
        if (!shoperId && this.curlistShoper === '') {
          this.$message.error('您未选择骑手')
          return false
        }
        const params = {ids:orderId? [orderId]: this.curlistOrder.ids, driverId:shoperId ? shoperId : this.curlistShoper}
        this.$http.post('/server/order/paotuiSetRiderOrder', JSON.stringify(params)).then(res => {
          if (res.data.success) {
            this.$message({type: 'success', message: '派单成功'})
          }
        })
      },
      toObtainARider() { //获取骑手
        const loading = this.$loading({
          lock: true,
          text: '获取骑手中...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)',
          target: document.querySelector('#shopper-list')
        })
        const params = {name: this.name}
        paotuiFindShopper(params).then(res => {
          if (res.success) {
            this.shopworkList = res.data
            this.showShoper()
          }
        }).finally(() => { loading.close() })
      },
      createWebSocket() { // 创建websocket
        try {
          const loginMsg = sessionStorage.getItem('loginMsg') || '{}'
          const p  = JSON.parse(loginMsg)
          if ('WebSocket' in window) {
            this.ws = new WebSocket(this.comConfig.path + '/paotuiWebsocket/diaodu/' + p.user + '/' + p.type + '/' + p.token)
          } else if ('MozWebSocket' in window) {
            this.ws = new WebSocket(this.comConfig.path + '/paotuiWebsocket/diaodu/' + p.user + '/' + p.type + '/' + p.token)
          } else {
            this.$alert("您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器，请勿使用IE10以下浏览器，360浏览器请使用极速模式，不要使用兼容模式！"); 
          }
          this.websocket()
        } catch(e) {
          this.reconnect()
          console.log(e)
        }     
      },
      reconnect() { // websocket 重新链接
        if (!this.stopWebSocket) {
          if(this.lockReconnect) return
          this.lockReconnect = true
          this.reastWebsocket = setTimeout(() => { // 没连接上会一直重连，设置延迟避免请求过多
            this.resall()
            this.lockReconnect = false
          }, 2000)
        }
      },
      websocket() {
        this.ws.onclose = () => {
          if (!this.stopWebSocket) {
            this.reconnect()
            console.log("跑腿连接关闭, 开始重连"+new Date().toUTCString())
          } else {
            console.log('跑腿-页面离开，不再重连'+new Date().toUTCString())
          }
        }
        this.ws.onerror = () => {
          this.reconnect()
          console.log('跑腿连接错误, 开始重连!'+new Date().toUTCString())
        };
        this.ws.onopen = () => {
          this.heartCheck() // 心跳检测重置
          console.log('跑腿连接成功!'+new Date().toUTCString())
        }
        this.ws.onmessage = evt => {
          this.heartCheck() // 心跳检测重置
          if (evt.data.indexOf('helle word') === -1) {
            const data = JSON.parse(evt.data) 
            if (data.paotuiOrder) {
              this.wsOrder(data.paotuiOrder)
              this.wsInbution(data.paotuiOrder)
              this.wsIunusual(data.paotuiOrder)
              this.wsTimeout(data.paotuiOrder)
              if(this.videoSet && this.neworder){
                try {
                  this.neworder.play()
                } catch(Exception) {
                  this.$alert('根据浏览器安全策略，需用户交互后才可以语言播报，请点击下方确认按钮！即交互！')
                }
              }
            }
            if (data.shopper) this.wsShoper(data.shopper)
          }
        }
      },
      heartCheck() { // 心跳
        clearTimeout(this.timeoutObj)
        this.timeoutObj = null
        this.timeoutObj = setTimeout(() =>{
          if (this.ws.readyState === 1) {
            this.ws.send('helle word')
          } else {
            console.log('跑腿链接后台关闭，尝试重新链接'+new Date().toUTCString())
            this.reconnect()
          }
        }, 60000)
      },
      getOrderScheduling() { //获取订单
        const loading = this.$loading({
          lock: true,
          text: '获取订单中...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)',
          target: document.querySelector('#order-list')
        })
        paotuiOrderSchedulingList().then(res => {
          if (res.success) {
            this.orders = res.data
            this.orders.list5 = []; this.orders.list6 = []
            if (res.data.list2.length > 0) {
              res.data.list2.forEach((item, index) => {
                if (this.capStatus(item.status) === 3) this.orders.list5.push(item)
                else if (this.capStatus(item.status) === 4) this.orders.list6.push(item)
              })
            }
             this.createWebSocket()
          } else {
            console.log('跑腿接口异常，页面已终止服务') 
          }
        }).catch(() => {
         this.$notify({
            title: '网络异常！',
            message: '跑腿订单获取失败，60秒后尝试自动重新请求！',
            duration: 60000
          })
          console.log('网络异常，60秒后重新调用跑腿订单接口')
          this.restOrderTime = setTimeout(() => {
            this.resall()
          }, 60000)
        }).finally(() => { loading.close() })
      },
      wsInbution(val) {
        const index1 = this.orders.list2.findIndex(item => item.id == val.id)
        const index2 = this.orders.list5.findIndex(item => item.id == val.id)
        const index3 = this.orders.list6.findIndex(item => item.id == val.id)
        //全部里显示与隐藏
        if (index1 > -1) {
          if (val.abnormal === 1) this.orders.list2.splice(index1, 1)
          else {
            if (this.capStatus(val.status) ==3 || this.capStatus(val.status) === 4) this.orders.list2.splice(index1, 1)
            else this.orders.list2.splice(index1, 1)
          }
        } else {
          if (val.abnormal === 1) {
          } else {
            if (this.capStatus(val.status) ==3 || this.capStatus(val.status) === 4) this.orders.list2.push(val)
          }
        }
        //找到了必是删除
        if (index2 >= '0') this.orders.list5.splice(index2, 1) // 前往商家
        else {
          if (this.capStatus(val.status) === 3 && val.abnormal !== 1) this.orders.list5.push(val)
        }
        if (index3 >= '0') this.orders.list6.splice(index3, 1) //待取货
        else{
          if (this.capStatus(val.status) === 4 && val.abnormal !== 1) this.orders.list6.push(val)
        }
      },
      reassigningTheRider(orderid, driverId) { //订单改派
        this.radioOrderId = orderid
        this.curShopper = driverId
        this.dialogTableVisible = true
      },
      saveChangeShopper() {//订单改派
        let id = this.radioOrderId
        let driverId = this.radioShopper
        if (id == this.curShopper) {
          this.$message.error('骑手未发生变化！')
          return false
        }
        let params = {id, driverId}
        this.$http.get('/server/order/paotuiEditOrderRider?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.dialogTableVisible = false
            this.$message.success('订单改派成功!')
          }
        })
      },
      alterTheState(orderid,type) {//修改状态
        let id = orderid,status = type
        this.$http.get('/server/order/paotuiEditOrderStatus?' + this.qs.stringify({id,status})).then(res => {
          if (res.data.success) {
            this.$message.success('修改状态成功!')
          }
        })
      },
      wsIunusual(val) {
        let cIndex = ''
        if (this.orders.list3.length > 0) {
          this.orders.list3.forEach((item, index) => {
            if (item.id == val.id) {
              cIndex = index
              return
            }
          })
        }
        if (cIndex >= '0') {
          if (val.abnormal == '1') this.$set(this.orders.list3, cIndex, val)
          else this.orders.list3.splice(cIndex, 1)
        } else {
          if (val.abnormal == '1') this.orders.list3.push(val)
        }
      },
      wsTimeout(val) {
        if(val.timePaid && val.deliveryDuration){
          const endTime = new Date(val.timePaid.replace(/-/g, "/")).getTime() + val.deliveryDuration*60000
          const nowTime = new Date().getTime()
          if (this.capStatus(val.status) === 5 && (endTime - nowTime) <= 0) this.orders.list4.push(val)
        }
      },
      resall() {
        this.toObtainARider()
        this.getOrderScheduling()
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.neworder = document.getElementById('appleline')
      })
      this.resall()
    },
    destroyed() {
      this.stopWebSocket = true
      clearTimeout(this.reastWebsocket)
      clearTimeout(this.timeoutObj)
      if (this.restOrderTime) clearTimeout(this.restOrderTime)
      if (this.ws) this.ws.close()
    }
  }
</script>

<style lang="scss" scoped>
  @import '../css/header.css';
  @import '../css/adjust.scss';

</style>
